/**
* AutoSWF - Cody Cushing. March 26, 2009
* Copyright (c) 2009 Cody Cushing
* No use restrictions. Maintain this notice in all versions. 
**/

package com.autoswf.taskrunner
{
	import com.autoswf.core.Link;
	import com.autoswf.core.Transport;
	import com.autoswf.taskrunner.loadtasks.LoadTaskFactory;
	
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;


	/**
	 * Ties a task runner into the application network, loads registered task factory by request type.
	 */
	public class Tasker extends Link
	{
		protected var _taskFactories:Dictionary;
		
		protected var _taskFactory:LoadTaskFactory;
		protected var _taskRunner:TaskRunner;
		protected var _taskModel:TaskModel;
		
		
		/**
		 * Constructor.
		 */		
		public function Tasker(id:String)
		{
			super(id);
			
			_taskFactories = new Dictionary();
			
			_taskRunner = new TaskRunner();
			_taskModel = new TaskModel(_taskRunner);
		}
		
		
		/**
		 * Makes an ITaskFactory available to convert IRequests into ITasks for execution in the TaskModel.
		 * 
		 * @param requestDef  An IRequest implementer that an ITaskFactory can convert to an ITask.
		 * @param factory  An ITaskFactory to be mapped to a specific IRequest implementer.
		 */		
		public function registerRequestToFactory(requestDef:Class, factory:Object):void
		{
			var className:String = getQualifiedClassName(requestDef);
			_taskFactories[className] = factory;
		}
		
		
		/**
		 * Intercepts IRequests and loads them in the task runner suite. Continues bubbling if there
		 * is no associated task factory for the type.
		 */		
		override public function sendUp(object:*):void
		{
			var transport:Transport = Transport(object);
			
			if(transport.message is IRequest)
			{
				var request:IRequest = IRequest(transport.message);
				
				var className:String = getQualifiedClassName(request);
				
				var taskFactory:ITaskFactory = _taskFactories[className];
				
				if(taskFactory)
				{
					_taskRunner.taskFactory = taskFactory;
					_taskModel.addTask(request);
					return;
				}
			}
			
			/* Bubble transport even if it's an IRequest that this Tasker couldn't handle. */
			notifyParents(transport);
		}
		
		
	}
}